<template>
  <div>
      <div class="top" >
          <el-input   style="width: 20%;margin: 10px 10px;" placeholder="请输入昵称" prefix-icon="el-icon-search" v-model="name" maxlength="20"></el-input>
          <el-select v-model="value" placeholder="请选择身份">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-button type="primary" icon="el-icon-search" @click="searchName">搜索</el-button>
          <el-button style="float: right;" type="primary" @click="handleAdd">添加<i class="el-icon-upload el-icon--right"></i></el-button>
      </div>
      <el-table :data="user" height="700" border stripe style="width: 100%">
        <el-table-column align="center" prop="id" label="id" width="80"></el-table-column>
        <el-table-column align="center" prop="username" label="用户名" width="80"></el-table-column>
        <el-table-column align="center" prop="phone" label="账号" width="120"></el-table-column>
        <el-table-column align="center"  label="性别" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.sex == '男'" type="cuccess"> <i class="el-icon-male"></i></el-tag>
            <el-tag v-else type="danger"><i class="el-icon-female"></i></el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="sign" label="个性签名" width="180"></el-table-column>
        <el-table-column align="center" prop="isAdmin" label="身份" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isAdmin == '1'" >员工</el-tag>
            <el-tag v-if="scope.row.isAdmin == '2'" >管理员</el-tag>
            <el-tag v-if="scope.row.isAdmin == '0'" >用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="avatar" label="头像" width="300">
          <template  slot-scope="{ row }">
            <img  style="width:300px;height: 200px" :src="row.avatar"  alt=""  />
          </template>
        </el-table-column> 
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit"  @click="handleUpdata(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete"  @click="handleDel(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :visible.sync="addVisible" :modal-append-to-body="false" width="60%" top="0" title="新增" :before-close="Close" >
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
              <el-input  v-model="ruleForm.username" ></el-input>
            </el-form-item>
            <el-form-item label="账号" prop="phone">
              <el-input  v-model="ruleForm.phone" ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPassword">
              <el-input type="password" v-model="ruleForm.checkPassword" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="ruleForm.sex">
                <el-radio  label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="员工？" prop="isAdmin">
              <el-radio-group v-model="ruleForm.isAdmin">
                <el-radio  label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="个性签名" prop="sign">
              <el-input  v-model="ruleForm.sign" ></el-input>
            </el-form-item>
            <el-form-item label="图片" prop="avatar">
              <el-upload class="avatar-uploader"  action="http://127.0.0.1:3000/v1/upload/upload" :show-file-list="false" :on-success="handleAvatarSuccess"  >
                <img style="width: 200px" v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addReset('ruleForm')">重置</el-button>
          <el-button type="primary" @click=" add('ruleForm')">提交</el-button>
        </span>
      </el-dialog>
      <el-dialog :visible.sync="updataVisible" :modal-append-to-body="false" width="60%" top="0" title="修改" :before-close="Close" >
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
              <el-input  v-model="ruleForm.username" ></el-input>
            </el-form-item>
            <el-form-item label="账号" prop="phone">
              <el-input  v-model="ruleForm.phone" ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input  type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <!-- <el-form-item label="确认密码" prop="checkPassword">
              <el-input type="password" v-model="ruleForm.checkPassword" autocomplete="off"></el-input>
            </el-form-item> -->
            <el-form-item label="性别" prop="sex">
              <el-input   v-model="ruleForm.sex" autocomplete="off"></el-input>
              <!-- <el-radio-group v-model="ruleForm.sex">
                <el-radio  label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group> -->
            </el-form-item>
            <el-form-item label="员工" prop="isAdmin">
              <el-radio-group v-model="ruleForm.isAdmin">
                <el-radio  label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="个性签名" prop="sign">
              <el-input  v-model="ruleForm.sign" ></el-input>
            </el-form-item>
            <el-form-item label="图片" prop="avatar">
              <!-- <img style="width: 200px"  :src="imageUrl" class="avatar"> -->
              <el-upload class="avatar-uploader" action="http://127.0.0.1:3000/v1/upload/upload" :show-file-list="false" :on-success="handleAvatarSuccess"  >
                <img style="width: 200px" v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updataReset('ruleForm')">重置</el-button>
          <el-button type="primary" @click=" updata('ruleForm')">提交</el-button>
        </span>
      </el-dialog>
  </div>

</template>

<script>
import myaxios from '../http/MyAxios'
import { BASE_URL } from '@/config'
  export default {
    data() {
            
      var Pass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPassword !== '') {
            this.$refs.ruleForm.validateField('checkPassword');
          }
          callback();
        }
      };
      var Pass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        options: [{
          value: '0',
          label: '用户'
        }, {
          value: '1',
          label: '员工'
        }, {
          value: '2',
          label: '管理员'
        },
        {
          value: '3',
          label: '全部'
        }],
        value: '3',
        user:[],
        id:0,
        name:'',
        imageUrl: '',
        addVisible: false,
        updataVisible:false,
        form:[],
        ruleForm: {
          isAdmin:'',
          username:'',
          phone: '',
          password: '',
          checkPassword: '',
          sign:'',
          sex:''
         
        },
        rules:{
          isAdmin:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
          sex:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
          sign:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
          username:[
          {required:true,message:'该字段必填',trigger:'blur'},
          ],
          phone:[
            {required:true,message:'该字段必填',trigger:'blur'},
            {
              pattern:/^1[3-9]\d{9}$/,
              message:'手机号格式不正确',
              trigger:'blur'
            }
          ],
          password:[
            {required:true,message:'该字段必填',trigger:'blur'},
            {min:6,max:9,message:'长度6-9',trigger:'blur'},
            { validator: Pass, trigger: 'blur' }
           
          ],
          checkPassword:[
            {required:true,message:'该字段必填',trigger:'blur'},
            { validator: Pass2, trigger: 'blur' }
          ]
        }
      }
    },
    beforeMount(){
      this.getUser()
    },
    methods: {
      handleAvatarSuccess(res) {
        this.imageUrl = res.result;

      },
      updataReset(formName) {
        this.$refs[formName].resetFields();
        this.ruleForm = {}
      },
      updata(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
          this.form.id = this.id
           this.form.username =  this.ruleForm.username
           this.form.phone =  this.ruleForm.phone
           this.form.password =  this.ruleForm.password
           this.form.sign =  this.ruleForm.sign
           this.form.sex =  this.ruleForm.sex
           this.form.avatar =  this.imageUrl
           this.form.doller = 100,
           this.form.isAdmin = this.ruleForm.isAdmin
            let url=BASE_URL + '/v1/user/userUpdate'
              myaxios.post(url,this.form).then(()=>{
                this.$message({
                  showClose: true,
                  message: '恭喜你，修改成功',
                  type: 'success'
                });

                this.getUser()
                this.updataVisible = false
                }).catch(err=>{
                    console.warn(err);
                  })
          } else {
            alert('提交失败');
            return false;
          }
        });
      },
      handleUpdata(row){
        this.id = row.id
        this.imageUrl = row.avatar
        console.log(row);
        let url=BASE_URL + '/v1/user/idSearch'
        let params = {id:this.id}
        myaxios.get(url,params).then(res=>{
          this.ruleForm = res.data.data[0]
          this.updataVisible = true
        }).catch(err=>{
          console.warn(err);
        })
      },
      addReset(formName) {
        this.$refs[formName].resetFields();
      },
      add(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
           this.form.username =  this.ruleForm.username
           this.form.phone =  this.ruleForm.phone
           this.form.password =  this.ruleForm.password
           this.form.sign =  this.ruleForm.sign
           this.form.sex =  this.ruleForm.sex
           this.form.avatar =  this.imageUrl
           this.form.doller = 100,
           this.form.isAdmin = this.ruleForm.isAdmin
            let url=BASE_URL + '/v1/user/userAdd'
              myaxios.post(url,this.form).then(()=>{
                this.$message({
                  showClose: true,
                  message: '恭喜你，提交成功',
                  type: 'success'
                });
                this.getUser()
                this.addVisible = false
                }).catch(err=>{
                    console.warn(err);
                  })
          } else {
            alert('提交失败');
            return false;
          }
        });
      },
      handleAdd(){
        this.ruleForm = {}
       this.addVisible = true
       this.imageUrl = ''
      },
      handleDel(row) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let url=BASE_URL + '/v1/user/userDelete'
          let params = {id:row.id}
            myaxios.get(url,params).then(()=>{
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.getUser()
              }).catch(err=>{
                    console.warn(err);
                 })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      Close(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      searchName(){
        let url = BASE_URL + '/v1/user/adminSearch'
        const params = {
          isAdmin: this.value,
          username: this.name
        }
        
        myaxios.get(url, params)
          .then(res => {
            if (res.data.code === 200) {
              this.user = res.data.data
              if (this.user.length === 0) {
                this.$message({
                  showClose: true,
                  message: '未找到相关用户',
                  type: 'info'
                })
              }
            } else {
              this.$message({
                showClose: true,
                message: res.data.message || '未找到相关用户',
                type: 'warning'
              })
            }
          })
          .catch(err => {
            console.error('Search error:', err)
            this.$message({
              showClose: true,
              message: '查询失败，请稍后重试',
              type: 'error'
            })
          })
      },
      getUser(){
        let url=BASE_URL + '/v1/user/allSearch'
        myaxios.get(url).then(res=>{
          this.user = res.data.data
        }).catch(err=>{
          console.warn(err);
        })
    },
    },
  }
</script>
<style scoped lang="scss">

</style>